package com.giscloud.amp.controller.auth;

import cn.hutool.core.collection.CollectionUtil;
import com.giscloud.amp.controller.BaseController;
import com.giscloud.amp.entity.dto.AmpAuthDTO;
import com.giscloud.amp.entity.dto.AmpStaffAuthDTO;
import com.giscloud.amp.entity.dto.AmpStaffAuthRelDTO;
import com.giscloud.amp.entity.vo.AmpAuthVO;
import com.giscloud.amp.entity.vo.AmpMenuVO;
import com.giscloud.amp.entity.vo.AmpStaffAuthVO;
import com.giscloud.amp.entity.vo.RoutesVO;
import com.giscloud.amp.service.auth.AmpAuthService;
import com.giscloud.amp.service.auth.AmpStaffAuthService;
import com.giscloud.commons.model.Result;
import com.giscloud.commons.utils.StringUtils;
import com.giscloud.token.utils.TokenUserUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author:gxd
 * @Description:
 * @Date: 17:24 2018/2/24
 * @Modified By:
 */
@SuppressWarnings("SpringJavaAutowiringInspection") //加这个注解让IDE 不报: Could not autowire
@RestController
@Log4j2
public class AmpAuthController extends BaseController {
    @Autowired
    private AmpAuthService ampAuthService;
	@Autowired
    private AmpStaffAuthService ampStaffAuthService;
    @Value("${giscloud.systemCode:limp}")
    private  String systemCode;
    @Autowired
    private TokenUserUtil tokenUserUtil;
    /**
     * 根据条件获取左侧菜单信息
     * @return
     */
    @RequestMapping("/amp/ampauth/getAmpAuthByCondition")
    public Result<List<RoutesVO>> getAmpAuthByCondition(@RequestBody AmpStaffAuthRelDTO auth){
        AmpStaffAuthRelDTO ampStaffAuthRelDTO = new AmpStaffAuthRelDTO();
        ampStaffAuthRelDTO.setStaffId(tokenUserUtil.getUserId());
        log.debug("staffId:"+ tokenUserUtil.getUserId());
        ampStaffAuthRelDTO.setRoles(tokenUserUtil.getRolesId());
        log.debug("rolesId:"+tokenUserUtil.getRolesId());
        //ampStaffAuthRelDTO.setSystemCode(systemCode);
        ampStaffAuthRelDTO.setSystemId(auth.getSystemId());
        ampStaffAuthRelDTO.setAuthTypes(Arrays.asList(new String[]{"url","expand"}));
        List<AmpMenuVO> allAmpAuth = ampAuthService.getAmpAuthByStaffAuthRel(ampStaffAuthRelDTO);
        List<RoutesVO> routesVOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(allAmpAuth)){
            Long topParentId = 0L;
            Map<Long,List<RoutesVO>> routesMap = new HashMap<>();
            for(AmpMenuVO ampMenuVO:allAmpAuth){
                if(topParentId > ampMenuVO.getParentId()){
                    topParentId = ampMenuVO.getParentId();
                }
                if(routesMap.get(ampMenuVO.getParentId()) == null){
                    routesMap.put(ampMenuVO.getParentId(),new ArrayList<>());
                }
                RoutesVO routesVO = new RoutesVO();
                routesVO.setId(ampMenuVO.getAuthId());
                routesVO.setParentId(ampMenuVO.getParentId());
                routesVO.setName(ampMenuVO.getAuthName());
                routesVO.setIcon(ampMenuVO.getModelStyle());
                routesVO.setPath(ampMenuVO.getUrl());
                routesVO.setComponent("."+ampMenuVO.getUrl());
                routesMap.get(ampMenuVO.getParentId()).add(routesVO);
            }
            routesVOS = routesMap.get(topParentId);
            //递归方法，组装树
            toTree(routesVOS,routesMap);
        }
        return Result.success(routesVOS);
    }

    /**
     * 递归方法，组装树
     * @param routesVOS
     * @param routesMap
     */
    private void toTree(List<RoutesVO> routesVOS,Map<Long,List<RoutesVO>> routesMap){
        for(RoutesVO routesVO : routesVOS){
            if(routesMap.containsKey(routesVO.getId())){
                routesVO.setComponent(null);
                routesVO.setRoutes(routesMap.get(routesVO.getId()));
                toTree(routesVO.getRoutes(),routesMap);
            }
        }
    }

    @RequestMapping("/amp/ampauth/findAuthByExample")
    public List<AmpAuthVO> findAuthByExample(@RequestBody AmpAuthDTO auth){
        return ampAuthService.findAuthByExample(auth);
    }

    @RequestMapping(value="/amp/ampauth/add",method = RequestMethod.POST)
    public Result add(@RequestBody AmpAuthDTO ampAuthDTO){
        try {
            ampAuthDTO.setCreatedStaffId(tokenUserUtil.getUserId());
            if(ampAuthService.insert(ampAuthDTO) >= 1){
                return Result.success("","更新成功");
            }else{
                return Result.error("提交失败");
            }
        }catch (Exception e){
            log.error("",e);
            return Result.error("提交失败");
        }
    }

    @RequestMapping(value="/amp/ampauth/edit",method = RequestMethod.POST)
    public Result edit(@RequestBody AmpAuthDTO ampAuthDTO){

        try {
            AmpAuthDTO ampAuthDTO2 = new AmpAuthDTO();
            ampAuthDTO2.setAuthId(ampAuthDTO.getAuthId());
            List<AmpMenuVO> list = ampAuthService.getAmpAuthByCondition(ampAuthDTO2);
            if(CollectionUtil.isNotEmpty(list)){
                ampAuthDTO.setOldValue(StringUtils.getOldValue(list.get(0)));
            }
            if(ampAuthService.update(ampAuthDTO) >= 1){
                return Result.success("","更新成功");
            }else{
                return Result.error("提交失败");
            }
        }catch (Exception e){
            return Result.error("提交失败");
        }
    }

    @RequestMapping(value="/amp/ampauth/delete",method = RequestMethod.POST)
    public Result delete(@RequestBody AmpStaffAuthDTO ampStaffAuthDTO){
        if(ampStaffAuthDTO.getAuthId() == null){
            return Result.error(-1,"删除失败，authID不能为空");
        }
        if (ampAuthService.delete(ampStaffAuthDTO.getAuthId()) >= 1) {
            return Result.success("","删除成功");
        } else {
            return Result.error(-1,"删除失败");
        }
    }
	
	@RequestMapping("/amp/ampauth/findAuthByStaffAndRole")
    public List<AmpStaffAuthVO> findAuthByStaffAndRole(@RequestBody AmpStaffAuthDTO ampStaffAuthDTO){
        return ampStaffAuthService.findAuthByStaffAndRole(ampStaffAuthDTO);
    }

    /**
     * 根据条件获取菜单信息
     * @return
     */
    @RequestMapping("/amp/ampauth/findAuthByMenu")
    public Result findAuthByMenu(@RequestBody AmpAuthDTO ampAuthDTO){
        List<AmpMenuVO> authList = ampAuthService.getAmpAuthByCondition(ampAuthDTO);
        return Result.success(authList);
    }

}
